package com.fordmotor.exception;

import com.fordmotor.pojo.ResponseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice(basePackages = {"com.fordmotor"})
public class LocationExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(LocationExceptionHandler.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map handle(Exception e) {
        ResponseVO respResultVO = new ResponseVO();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(baos));
        String exception = baos.toString();
        logger.error(exception);
        Map<String,Object> errorMap = new HashMap<>();
        errorMap.put("time_stamp", Instant.now().getEpochSecond()+"");
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("exception",e.getClass().getName());
        resultMap.put("message",e.getMessage());
        if (e instanceof BasicErrorCodeException) {
            logger.error("请求异常{}", ((BasicErrorCodeException) e).getErrorMessage().getCode(), ((BasicErrorCodeException) e).getErrorMessage().getMsg());
            BasicErrorCodeException ex = (BasicErrorCodeException) e;
            respResultVO.setErrcode(((BasicErrorCodeException) ex).getErrorMessage().getCode());
            respResultVO.setErrmsg(((BasicErrorCodeException) ex).getErrorMessage().getMsg());
        }else if(e instanceof RuntimeErrorCodeException) {
            logger.error("请求异常{}", ((RuntimeErrorCodeException) e).getRuntimeError().getCode(), ((RuntimeErrorCodeException) e).getRuntimeError().getMsg());
            RuntimeErrorCodeException ex = (RuntimeErrorCodeException) e;
            respResultVO.setErrcode(((RuntimeErrorCodeException)ex).getRuntimeError().getCode());
            respResultVO.setErrmsg(((RuntimeErrorCodeException) ex).getRuntimeError().getMsg());
        }else{
            logger.error("系统异常{}", e, e.getMessage());
            respResultVO.setErrcode(RuntimeError.SYSTEM_ERROR.getCode());
            respResultVO.setErrmsg(RuntimeError.SYSTEM_ERROR.getMsg());
        }
        errorMap.put("result",respResultVO);
        return errorMap;
    }


}
